
import * as address from '@/api/address'
import { getUserInfoAndAddress } from '@/common/common'
const state = {
  // 用户收获地址列表
  userAddressList: []
}

const mutations = {

  // 保存用户收获地址列表
  SET_USERADDRESSLIST: (state, addressList) => {
    state.userAddressList = addressList
  }
}

const actions = {

  // 设置默认地址
  setDefaultAdd({ commit, dispatch, state }, payload) {
    return new Promise((resolve, reject) => {
      address.setDefaultAdd(payload).then(res => {
        getUserInfoAndAddress().then(res => {
          resolve(res)
        })
      }).catch(error => {
        reject(error)
      })
    })
  },

  // 添加收货地址
  addAddress({ commit, state, dispatch }, addressQo) {
    return new Promise((resolve, reject) => {
      address.addUserAddress(addressQo).then(res => {
        resolve(res)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // 获取用户收获地址
  getUserAddress({ commit, state }, uid) {
    return new Promise((resolve, reject) => {
      address.getAddress(uid).then(res => {
        commit('SET_USERADDRESSLIST', res.object)
        resolve(res)
      }).catch(() => {
        reject('获取用户收获地址失败')
      })
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
